import {
  convertTxtToMock,
  processLargeTxt,
  validateChapters,
  exportChaptersToJson,
  previewChapters,
  TxtToMockUtils,
} from "./txtToMock";

// 示例TXT内容（斗罗大陆格式）
const sampleTxtContent = `
第一章 唐门外门弟子

蓝银草，是最没用的武魂之一，几乎没有任何攻击能力。同时，也是最常见的武魂之一，在诺丁学院，至少有八成的学员都拥有蓝银草武魂。

唐三今年六岁，先天魂力半级，拥有蓝银草武魂。

"唐三，你又在发呆。"素云涛不悦的声音将唐三从沉思中唤醒。

第二章 穿越者的第二人生

唐三并不是这个世界的人，他来自另外一个世界，一个没有魂力，没有武魂的世界。

在那个世界中，他是唐门的一名外门弟子，精通各种暗器的制造和使用。

但是，唐门有一条铁律：唐门绝学，不得外传。

第三章 觉醒

"好了，现在开始测试你们的武魂。"素云涛说道，"先从你开始，唐三。"

唐三走上前去，将手放在水晶球上。

蓝色的光芒从水晶球中绽放出来，一株蓝银草的虚影出现在唐三身后。

"蓝银草武魂，先天魂力半级。"素云涛记录着。
`;

/**
 * 基本使用示例
 */
export function basicExample() {
  console.log("=== 基本使用示例 ===");

  // 转换TXT为Mock数据
  const chapters = convertTxtToMock(sampleTxtContent, {
    novelId: "douluo",
    novelTitle: "斗罗大陆",
    freeChapters: 2, // 前2章免费
    vipPrice: 10,
  });

  console.log("转换结果：", chapters);
  console.log("章节数量：", chapters.length);

  // 验证数据
  const validation = validateChapters(chapters);
  console.log("验证结果：", validation);

  return chapters;
}

/**
 * 大文件处理示例
 */
export async function largeFileExample(file: File) {
  console.log("=== 大文件处理示例 ===");

  try {
    const chapters = await processLargeTxt(file, {
      novelId: "large-novel",
      novelTitle: "大型小说",
      freeChapters: 50,
      vipPrice: 15,
      chunkSize: 512 * 1024, // 512KB分块
    });

    console.log("处理完成，章节数量：", chapters.length);

    // 预览前5章
    const preview = previewChapters(chapters, 5);
    console.log("前5章预览：", preview);

    // 验证数据
    const validation = validateChapters(chapters);
    console.log("数据统计：", validation.statistics);

    if (validation.errors.length > 0) {
      console.warn("发现错误：", validation.errors);
    }

    return chapters;
  } catch (error: any) {
    console.error("文件处理失败：", error);
    throw error;
  }
}

/**
 * 自定义章节模式示例
 */
export function customPatternExample() {
  console.log("=== 自定义章节模式示例 ===");

  // 英文章节格式的TXT
  const englishTxt = `
Chapter 1: The Beginning

This is the content of chapter 1...

Chapter 2: The Journey Continues

This is the content of chapter 2...

Chapter 3: The Final Battle

This is the content of chapter 3...
`;

  // 使用自定义正则表达式处理
  const chapters = englishTxt
    .split(TxtToMockUtils.chapterPatterns.english)
    .filter(Boolean)
    .reduce((result, item, index) => {
      if (index % 2 === 0) {
        // 章节标题
        const title = item.trim();
        const content = englishTxt.split(TxtToMockUtils.chapterPatterns.english)[index + 1]?.trim();

        if (title && content) {
          result.push({
            id: `english-${Math.floor(index / 2) + 1}`,
            novelId: "english-novel",
            chapterNumber: Math.floor(index / 2) + 1,
            title: title,
            content: content,
            wordCount: content.length,
            isVip: Math.floor(index / 2) + 1 > 1,
            price: Math.floor(index / 2) + 1 > 1 ? 10 : 0,
            isFree: Math.floor(index / 2) + 1 <= 1,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
          });
        }
      }
      return result;
    }, [] as any[]);

  console.log("英文章节处理结果：", chapters);
  return chapters;
}

/**
 * 批量处理示例
 */
export async function batchProcessExample(files: FileList) {
  console.log("=== 批量处理示例 ===");

  const results = [];

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    console.log(`处理文件 ${i + 1}/${files.length}: ${file.name}`);

    try {
      const chapters = await processLargeTxt(file, {
        novelId: `novel-${i + 1}`,
        novelTitle: file.name.replace(".txt", ""),
        freeChapters: 30,
        vipPrice: 12,
      });

      results.push({
        filename: file.name,
        chapters: chapters.length,
        success: true,
        data: chapters,
      });

      console.log(`✅ ${file.name} 处理完成，共 ${chapters.length} 章`);
    } catch (error) {
      console.error(`❌ ${file.name} 处理失败：`, error);
      results.push({
        filename: file.name,
        chapters: 0,
        success: false,
        error: (error as Error).message,
      });
    }
  }

  console.log("批量处理完成：", results);
  return results;
}

/**
 * 导出功能示例
 */
export function exportExample() {
  console.log("=== 导出功能示例 ===");

  // 生成示例数据
  const chapters = convertTxtToMock(sampleTxtContent, {
    novelId: "export-demo",
    novelTitle: "导出示例",
    freeChapters: 1,
    vipPrice: 8,
  });

  // 导出为JSON文件
  exportChaptersToJson(chapters, "douluo-chapters.json");

  console.log("数据已导出为 douluo-chapters.json");

  return chapters;
}

/**
 * Web界面集成示例
 */
export function createWebInterface() {
  console.log("=== Web界面集成示例 ===");

  // 创建文件上传界面
  const container = document.createElement("div");
  container.innerHTML = `
    <div style="padding: 20px; border: 1px solid #ccc; border-radius: 8px; margin: 20px;">
      <h3>TXT转Mock数据工具</h3>
      
      <div style="margin-bottom: 15px;">
        <label>选择TXT文件：</label>
        <input type="file" id="txtFile" accept=".txt" />
      </div>
      
      <div style="margin-bottom: 15px;">
        <label>小说ID：</label>
        <input type="text" id="novelId" value="novel" />
      </div>
      
      <div style="margin-bottom: 15px;">
        <label>小说标题：</label>
        <input type="text" id="novelTitle" value="小说" />
      </div>
      
      <div style="margin-bottom: 15px;">
        <label>免费章节数：</label>
        <input type="number" id="freeChapters" value="50" />
      </div>
      
      <div style="margin-bottom: 15px;">
        <label>VIP章节价格：</label>
        <input type="number" id="vipPrice" value="10" />
      </div>
      
      <button id="processBtn">处理文件</button>
      <button id="exportBtn" disabled>导出JSON</button>
      
      <div id="result" style="margin-top: 20px; padding: 10px; background: #f5f5f5; border-radius: 4px;"></div>
    </div>
  `;

  // 添加事件监听
  const processBtn = container.querySelector("#processBtn") as HTMLButtonElement;
  const exportBtn = container.querySelector("#exportBtn") as HTMLButtonElement;
  const resultDiv = container.querySelector("#result") as HTMLDivElement;

  let processedChapters: any[] = [];

  processBtn.addEventListener("click", async () => {
    const fileInput = container.querySelector("#txtFile") as HTMLInputElement;
    const novelIdInput = container.querySelector("#novelId") as HTMLInputElement;
    const novelTitleInput = container.querySelector("#novelTitle") as HTMLInputElement;
    const freeChaptersInput = container.querySelector("#freeChapters") as HTMLInputElement;
    const vipPriceInput = container.querySelector("#vipPrice") as HTMLInputElement;

    const file = fileInput.files?.[0];
    if (!file) {
      alert("请选择TXT文件");
      return;
    }

    try {
      processBtn.textContent = "处理中...";
      processBtn.disabled = true;

      processedChapters = await processLargeTxt(file, {
        novelId: novelIdInput.value,
        novelTitle: novelTitleInput.value,
        freeChapters: parseInt(freeChaptersInput.value),
        vipPrice: parseInt(vipPriceInput.value),
      });

      const validation = validateChapters(processedChapters);

      resultDiv.innerHTML = `
        <h4>处理完成！</h4>
        <p>总章节数：${validation.statistics.totalChapters}</p>
        <p>免费章节：${validation.statistics.freeChapters}</p>
        <p>VIP章节：${validation.statistics.vipChapters}</p>
        <p>总字数：${validation.statistics.totalWords.toLocaleString()}</p>
        <p>平均字数：${validation.statistics.averageWords}</p>
        ${validation.errors.length > 0 ? `<p style="color: red;">错误：${validation.errors.join(", ")}</p>` : ""}
      `;

      exportBtn.disabled = false;
    } catch (error: any) {
      resultDiv.innerHTML = `<p style="color: red;">处理失败：${error.message}</p>`;
    } finally {
      processBtn.textContent = "处理文件";
      processBtn.disabled = false;
    }
  });

  exportBtn.addEventListener("click", () => {
    const novelIdInput = container.querySelector("#novelId") as HTMLInputElement;
    exportChaptersToJson(processedChapters, `${novelIdInput.value}-chapters.json`);
  });

  return container;
}

// 导出所有示例函数
export default {
  basicExample,
  largeFileExample,
  customPatternExample,
  batchProcessExample,
  exportExample,
  createWebInterface,
};
